const DEL_ONE = 1
const DEL_OTHER = 2
const DEL_ALL = 3

const state = {
  visitedViews: [],
  cachedViews: []
}

const mutations = {
  ADD_VISITED_VIEW: (state, view) => {
    if (state.cachedViews.some(v => v.path === view.path)) return
    state.visitedViews.push({ ...view, title: view.meta.title || '-' })
  },
  DEL_VISITED_VIEW: (state, mode, view) => {
    state.visitedViews = state.visitedViews.filter(v => {
      return v.meta.affix || (mode === DEL_ONE && v.path === view.path) ||
        (mode === DEL_OTHER && v.path !== view.path) || mode === DEL_ALL
    })
  },
  ADD_CACHED_VIEW: (state, view) => {
    if (state.cachedViews.includes(view.name)) return
    if (!view.meta.noCache) state.cachedViews.push(view.name)
  },
  DEL_CACHED_VIEW: (state, mode, view) => {
    if (mode === DEL_ALL) {
      state.cachedViews = []
      return
    }
    const i = state.cachedViews.indexOf(view.name)
    if (i > -1) state.cachedViews.splice(i, 1)
  }
}

const actions = {
  addVisitedView({ commit }, view) { commit('ADD_VISITED_VIEW', view) },
  delVisitedView({ commit }, view) { commit('DEL_VISITED_VIEW', view) },
  addCachedView({ commit }, view) { commit('ADD_CACHED_VIEW', view) },
  delCachedView({ commit }, view) { commit('DEL_CACHED_VIEW', view) },
  addView({ dispatch }, view) {
    dispatch('addVisitedView', view)
    dispatch('addCachedView', view)
  },
  delView({ dispatch }, view) {
    dispatch('delVisitedView', view)
    dispatch('delCachedView', view)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

